package com.mars.pay.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mars.pay.common.PaymentStatusEnum;
import com.mars.pay.entity.Order;
import com.mars.pay.mapper.OrderMapper;
import com.mars.pay.utils.OrderNoGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 订单服务
 *
 * @author Mars
 */
@Slf4j
@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IService<Order> {

    /**
     * 创建订单
     *
     * @param productName 商品名称
     * @param productDesc 商品描述
     * @param amount      订单金额
     * @param userId      用户 ID
     * @return 订单
     */
    @Transactional(rollbackFor = Exception.class)
    public Order createOrder(String productName, String productDesc, BigDecimal amount, Long userId) {
        Order order = new Order();
        order.setOrderNo(OrderNoGenerator.generate());
        order.setProductName(productName);
        order.setProductDesc(productDesc);
        order.setAmount(amount);
        order.setStatus(PaymentStatusEnum.WAIT_PAY.getCode());
        order.setUserId(userId);
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        save(order);
        log.info("创建订单成功：订单号={}, 商品={}, 金额={}", order.getOrderNo(), productName, amount);
        
        return order;
    }

    /**
     * 根据订单号查询订单
     *
     * @param orderNo 订单号
     * @return 订单
     */
    public Order getByOrderNo(String orderNo) {
        return getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, orderNo));
    }

    /**
     * 根据 ID 查询订单
     *
     * @param orderId 订单 ID
     * @return 订单
     */
    public Order getByOrderId(Long orderId) {
        return getById(orderId);
    }

    /**
     * 更新订单支付状态
     *
     * @param orderNo      订单号
     * @param status       支付状态
     * @param thirdOrderNo 第三方订单号
     * @param paymentType  支付方式
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderStatus(String orderNo, Integer status, String thirdOrderNo, String paymentType) {
        Order order = getByOrderNo(orderNo);
        if (order == null) {
            log.warn("订单不存在：{}", orderNo);
            return;
        }
        
        order.setStatus(status);
        order.setThirdOrderNo(thirdOrderNo);
        order.setPaymentType(paymentType);
        order.setUpdateTime(LocalDateTime.now());
        
        if (PaymentStatusEnum.SUCCESS.getCode().equals(status)) {
            order.setPayTime(LocalDateTime.now());
        }
        
        updateById(order);
        log.info("更新订单状态：订单号={}, 状态={}", orderNo, status);
    }

    /**
     * 查询用户订单列表
     *
     * @param userId 用户 ID
     * @return 订单列表
     */
    public List<Order> listByUserId(Long userId) {
        return list(new LambdaQueryWrapper<Order>()
                .eq(Order::getUserId, userId)
                .orderByDesc(Order::getCreateTime));
    }

    /**
     * 查询所有订单列表
     *
     * @return 订单列表
     */
    public List<Order> listAll() {
        return list(new LambdaQueryWrapper<Order>().orderByDesc(Order::getCreateTime));
    }

    /**
     * 分页查询订单列表
     *
     * @param pageNum  页码
     * @param pageSize 每页数量
     * @return 订单列表
     */
    public List<Order> listByPage(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        return list(new LambdaQueryWrapper<Order>()
                .orderByDesc(Order::getCreateTime)
                .last("LIMIT " + offset + ", " + pageSize));
    }

    /**
     * 获取订单总数
     *
     * @return 总数
     */
    public long getTotalCount() {
        return count();
    }
}

